package controllers.batch;

import controllers.admin.permission.AuthorityController;
import controllers.deadbolt.RestrictedResource;
import models.batchlist.TutorBatch;
import models.batchlist.TutorList;
import models.tutor.Tutor;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.omg.CORBA.Object;
import play.db.jpa.JPA;
import play.modules.router.Get;
import play.modules.router.Post;
import utils.JSON;

import javax.persistence.Query;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


@RestrictedResource(name="/tts/batch")
public class Batchlist extends AuthorityController {

    @Get("/tts/batch")
    public static void batch() {  render();  }

    @Get("/tts/batch/data")
    public static void batchdata() {
        List<TutorBatch> batchs = TutorBatch.findAll();
        renderJSON(JSON.customExpose().toJson(batchs));
    }

    @Get("/tts/batchs/{id}")
    public static void tutorlist(long id){
        Query query = JPA.em().createQuery(
                "SELECT t.code, t.name, t.unit, t.tutorType, t.discipline FROM TutorList l,Tutor t WHERE l.code=t.code and l.batchid =:ID ");
        query.setParameter("ID",id);
        List<Object> tl = query.getResultList();
        renderJSON(JSON.customExpose().toJson(tl));
    }

    @Post("/tts/batch/add")
    public static void addbatch(String year) {
        TutorBatch batch = TutorBatch.find("byBatchyear",year).first();
        if(batch==null){
            batch = new TutorBatch();
            batch.batchyear = year;
            batch.isOpen = true;
            batch.status = true;
            batch.save();
        }
    }

    @Post("/tts/batch/toggle")
    public static void toggle(long id) {
        TutorBatch batch = TutorBatch.findById(id);
        if(batch!=null){
            batch.isOpen = !batch.isOpen;
            batch.save();
        }
    }

    /**
     * 导出导师名单上传模板
    @Get("/batch/getBatchTemplate")
    public static void getBatchTemplate(){
        VirtualFile xlsFile;
        for (VirtualFile vf : Play.javaPath) {
            xlsFile = vf.child("public/template/batchTemplate.xls");
            if (xlsFile != null && xlsFile.exists()) {
                File file = xlsFile.getRealFile();
                renderBinary(file);
                break;
            }
        }
    }
     */

    /**
     * 导入导师名单信息，重复上新纪录，而是覆盖前次上传结果。
     */
    @Post("/tts/batch/upload")
    public static void uploadTutors(long id, File file){
        try {
            //delete all old records
            TutorList.delete("batchid", id);

            //add new records
            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
            int rows = wb.getSheetAt(0).getPhysicalNumberOfRows();
            String result = "";
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row = null;
            HSSFCell cell = null;

            for (int i = 1; i < rows; i++) {
                row = sheet.getRow(i);
                cell = row.getCell((short) 0);
                cell.setCellType(Cell.CELL_TYPE_STRING);
                String code = cell.getStringCellValue().trim();
                Tutor tutor = Tutor.find(" code=? ", code).first();
                if(code==null || code.length()!=10){
                    result += "工号为"+code+"的记录非法<br>";
                }else{
                    TutorList vtutor = new TutorList();
                    vtutor.batchid = id;
                    vtutor.code = code;
                    vtutor.save();
                }
            }

            if(result.equals("")){
            	result = "导入成功";
            }
            renderText(result);
        } catch (Exception e) {
            e.printStackTrace();
            renderText(e.getMessage());
        }
    }
}